#!/bin/bash

THIS_AAF_PACKAGE="aaf-aliroot"
THIS_DIR=`pwd`
AAF_DIR="`cd ../../../../ ; pwd`"

echo " Installing $THIS_AAF_PACKAGE on `hostname -f` ..."

if [ ! -e $AAF_DIR/aaf.cf ];then
  echo "$AAF_DIR/aaf.cf was not found!!! Skipping postinstall for AAF ..."
  exit 0
fi


#  tar cf - "VO_ALICE@AliRoot::v4-19-18-AN" | gzip -f9 > "VO_ALICE@AliRoot::v4-19-18-AN.par"

#ROOT_VER="v5-34-02-1"
ROOT_VER="v5-34-05"
AFDSUtils_VER="1.0.0"

source $AAF_DIR/aaf.cf
ALIEN_PACKAGES_DIR="$ALICE_PROOF_AAF_ALIEN_PACKAGES"
PROOF_DIR="$ALICE_PROOF_AAF_PROOF_DIR"
PROOF_PACKAGES_DIR="$PROOF_DIR/packages/"
#PROOF_PACKAGES_LIST="VO_ALICE@AliRoot VO_ALICE@ROOT"
PROOF_PACKAGES_LIST="VO_ALICE@AliRoot"

if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
    PROOF_PACKAGES_LIST="VO_ALICE@AliRoot_CVMFS"
fi

function SyncOneAliEnPackage() {
  if [ ! -z $1 ];then
    MY_ALIEN_USER=`echo $1 | awk -F '@' '{print $1}'`
    MY_ALIEN_PACKAGE=`echo $1 | awk -F '@' '{print $2}'`
    MY_SW_DIR="$ALIEN_PACKAGES_DIR/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/"
    if [ "${AF_ALIROOT_DIR_TEMPLATE:0:6}" = "/cvmfs" ]; then
	MY_SW_DIR="/cvmfs/alice.cern.ch/x86_64-2.6-gnu-4.1.2/Packages/"
    fi
    if [ -d "$MY_SW_DIR" ]; then
      for MY_VER  in `ls $MY_SW_DIR`; do
	echo "    $MY_VER"
	if [ ! -d $PROOF_PACKAGES_DIR/$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER ];then
	  mkdir -p $PROOF_PACKAGES_DIR/$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER
	  cp -r $PROOF_DIR/aaf-aliroot/aaf-aliroot/PROOF-INF/$1/PROOF-INF/ $PROOF_PACKAGES_DIR/$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER/PROOF-INF
	  echo "cp -r $PROOF_DIR/aaf-aliroot/aaf-aliroot/PROOF-INF/$1/PROOF-INF/ $PROOF_PACKAGES_DIR/$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER/PROOF-INF"
	  HERETMP=`pwd`
	  cd $PROOF_PACKAGES_DIR/
	  tar cf - "$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER" | gzip -f9 > "$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER.par"
	  rm -Rf "$MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER"
	  cd $HERETMP
	fi
      done
    fi
  else
    echo "Empty package name !!!"
  fi
}

function SyncAFDSUtilsPar() {
  mkdir -p "$PROOF_PACKAGES_DIR/VO_ALICE@AFDSUtils::$AFDSUtils_VER"
  cp -r "$PROOF_DIR/aaf-aliroot/aaf-aliroot/PROOF-INF/VO_ALICE@AFDSUtils/PROOF-INF/" "$PROOF_PACKAGES_DIR/VO_ALICE@AFDSUtils::$AFDSUtils_VER/PROOF-INF"
  wget -O "$PROOF_PACKAGES_DIR/VO_ALICE@AFDSUtils::$AFDSUtils_VER/afdsutil.C" http://afdsmgrd.googlecode.com/svn/tags/v$AFDSUtils_VER/macros/par/afdsutil/afdsutil.C 
  HERETMP=`pwd`
  cd $PROOF_PACKAGES_DIR/
  tar cf - "VO_ALICE@AFDSUtils::$AFDSUtils_VER" | gzip -f9 > "VO_ALICE@AFDSUtils::$AFDSUtils_VER.par"
  rm -Rf "VO_ALICE@AFDSUtils::$AFDSUtils_VER"
  cd $HERETMP
}

function SyncAAFMacrosAndScripts() {

  mkdir -p $AAF_DIR/scripts > /dev/null 2>&1
  mkdir -p $AAF_DIR/macros > /dev/null 2>&1
  FILES_SCRIPTS="aaf.sh aaf-mlclient/aaf-mlclient.init.d aaf-installer aaf-installer.sh env_aliroot.bash PROOF_CMD.sh afdsmgrd-aaf-integration"
  FILES_SCRIPTS_EXEC="aaf.sh aaf-mlclient/aaf-mlclient.init.d aaf-mlclient/runMonalisa.sh aaf-installer aaf-installer.sh env_aliroot.bash PROOF_CMD.sh afdsmgrd-aaf-integration"
  FILES_MACROS="TestXrddm.C EnableGlobalParFile.C testAliRoot.C"  
  rm -f $AAF_DIR/scripts/aaf_alien_packages.sh > /dev/null 2>&1
  
  for f in $FILES_SCRIPTS; do
    mv $AAF_DIR/scripts/$f $AAF_DIR/scripts/$f.old > /dev/null 2>&1
    wget -O $AAF_DIR/scripts/$f http://xrootd-dm.googlecode.com/svn/trunk/etc/PROOF_AAF/scripts/$f > /dev/null 2>&1
  done

  for f in $FILES_SCRIPTS_EXEC; do
    chmod +x $AAF_DIR/scripts/$f
  done

  for f in $FILES_MACROS; do
    mv $AAF_DIR/macros/$f $AAF_DIR/macros/$f.old > /dev/null 2>&1
    wget -O $AAF_DIR/macros/$f http://xrootd-dm.googlecode.com/svn/trunk/etc/PROOF_AAF/macros/$f > /dev/null 2>&1
  done

#   wget -O $AAF_DIR/macros/$f http://xrootd-dm.googlecode.com/svn/trunk/etc/PROOF_AAF/macros/$f > /dev/null 2>&1
}

function GenerateAAFmlclientConfig() {

  # xrd-dm.cfg
  mkdir -p $AAF_DIR/scripts/aaf-mlclient > /dev/null 2>&1
  echo "# generated `date`" > $AAF_DIR/scripts/aaf-mlclient/aaf-mlclient.sysconfig
#   echo "export AAF_MLCLIENT=$ALICE_PROOF_AAF_ALIEN_DIR/lib/perl5/site_perl/5.8.8" >> $AAF_DIR/scripts/aaf-mlclient/aaf-mlclient.sysconfig
  echo "export AAF_MONALISA_DIR=$AAF_DIR/scripts/aaf-mlclient" >> $AAF_DIR/scripts/aaf-mlclient/aaf-mlclient.sysconfig
  echo "export AAF_MONALISA_USER=$ALICE_PROOF_AAF_USER" >> $AAF_DIR/scripts/aaf-mlclient/aaf-mlclient.sysconfig

  echo "# generated `date`" > $AAF_DIR/scripts/aaf-mlclient/runMonalisa.sh
  echo "source $AAF_DIR/aaf.cf" >> $AAF_DIR/scripts/aaf-mlclient/runMonalisa.sh
  echo "export AAF_MLCLIENT=$ALICE_PROOF_AAF_ALIEN_DIR/lib/perl5/site_perl/5.10.1:$ALICE_PROOF_AAF_ALIEN_DIR/lib/perl5/site_perl/5.8.8" >> $AAF_DIR/scripts/aaf-mlclient/runMonalisa.sh
  echo "export PERL5LIB=$PERL5LIB:\$AAF_MLCLIENT" >> $AAF_DIR/scripts/aaf-mlclient/runMonalisa.sh
  echo "perl $AAF_DIR/scripts/aaf-mlclient/perl_monalisa.pl > /dev/null &" >> $AAF_DIR/scripts/aaf-mlclient/runMonalisa.sh

}
function GenerateAAFmlclientPerlScript() {

# $AAF_DIR

MY_AAF_PROOF_CLUSTERNAME=`echo $ALICE_PROOF_AAF_XROOTD_SE_NAME | awk -F ':' '{print $3}'`
export MY_AAF_XROOTD_DIR_LATEST=""
for MY_XRD_VER in `ls -rt $ALICE_PROOF_AAF_DIR | grep xrootd_` ; do
  MY_AAF_XROOTD_DIR_LATEST="$MY_XRD_VER"
done

export MY_ROOT_VER=`ls -al $AAF_DIR/root | awk -F '-> ' '{print $2}'`
# export MY_ROOT_VER_DBG=`ls -al $AAF_DIR/root_dbg | awk -F '-> ' '{print $2}'`
rm -f $AAF_DIR/scripts/aaf-mlclient/perl_monalisa.pl

if [ ! -e $ALICE_PROOF_AAF_DIR/scripts/aaf-mlclient/aaf_status.txt ]; then
  echo "Maintenance since `date`" > $ALICE_PROOF_AAF_DIR/scripts/aaf-mlclient/aaf_status.txt
fi

cat > $AAF_DIR/scripts/aaf-mlclient/perl_monalisa.pl << EOF
# This example shows how ApMon can be used as a simple host sensor to monitor and send
# the desired parameters to the MonALISA service (configured in the given file/url)
use strict;
use warnings;

use Net::Domain;
use File::Spec;
use ApMon;

# redirect output
open STDOUT,">/dev/null";
open STDERR,">/dev/null";

my \$apm = new ApMon("http://aaf.cern.ch/config/monalisa_$MY_AAF_PROOF_CLUSTERNAME.conf");

my \$my_host = Net::Domain::hostfqdn();
my \$cluster="${ALICE_PROOF_AAF_XROOTD_SE_NAME}_xrootd_Nodes";

# TODO
my \$clusterMaster="${ALICE_PROOF_AAF_XROOTD_SE_NAME}_manager_xrootd_Services";
my \$masterHostname="${ALICE_PROOF_AAF_PROOF_MASTER}";

# the background data about the system will be sent with this cluster and node
#\$apm->setMonitorClusterNode(\$cluster, \$my_host);

# sleep forever
while(1){
  my \$count = 0;
  my \$countWorkers = 0;
  my \$aaf_status = "";
  if (\$masterHostname eq \$my_host){ 
    open(DATE, "ps ax -o user,command | grep proofserv.exe | grep -v grep | cut -f1 -d' ' | sort | uniq | wc -l |");
    \$count = <DATE>;
    close(DATE);
    
    open(DATE, "cat $ALICE_PROOF_AAF_PROOF_DIR/xproofd/proof.conf | grep -v '#' | grep 'worker' | wc -l|");
    \$countWorkers = <DATE>;
    close(DATE);


    open(DATE, "cat $ALICE_PROOF_AAF_DIR/scripts/aaf-mlclient/aaf_status.txt |");
    \$aaf_status = <DATE>;
    close(DATE);


  } else {
    open(DATE, "ps aux | grep 'proofslave' | grep -v grep | wc -l|");
    \$count = <DATE>;
    close(DATE);
  }
  chomp(\$count);


  my \$xproofdup = 0;
  open(DATE, "ps aux | grep bin/xproofd | grep -v grep | wc -l|");
  \$xproofdup = <DATE>;
  close(DATE);

  my \$xrootdup = 0;
  open(DATE, "ps aux | grep bin/xrootd | grep -v mps | grep -v grep | wc -l|");
  \$xrootdup = <DATE>;
  close(DATE);

  my \$olbdup = 0;
  open(DATE, "ps aux | grep bin/cmsd | grep -v grep | wc -l|");
  \$olbdup = <DATE>;
  close(DATE);

  my \$xrootd_ver = "n/a";
  open(DATE, "ps aux | grep 'xrootd -n manager' | grep -v grep |");
  \$xrootd_ver = <DATE>;
  close(DATE);

  if(\$xrootd_ver) {
    \$xrootd_ver = (split(/\s+/, \$xrootd_ver))[10];
    \$xrootd_ver =~ s/.*\/xrootd_(.+?)\/.*/\$1/;
  }
  else {
    \$xrootd_ver = "n/a";
  }

  my \$xrootd_ver_latest = "$MY_AAF_XROOTD_DIR_LATEST";
  if(\$xrootd_ver_latest) {
    \$xrootd_ver_latest =~ s/xrootd_//;
  }
  else {
    \$xrootd_ver_latest = "n/a";
  }

  my \$root_ver = File::Spec->splitpath("$MY_ROOT_VER");

  my \$proof_alias = "$ALICE_PROOF_AAF_XROOTD_REDIRECTOR";


  \$apm->sendParameters(\$cluster, \$my_host, { "proofserv_count" => \$count, "xproofd_up" => \$xproofdup, "xrootd_up" => \$xrootdup, "cmsd_up" => \$olbdup, "aaf_xrootd_ver" => \$xrootd_ver, "aaf_xrootd_ver_latest" => \$xrootd_ver_latest,"aaf_root_ver" => \$root_ver});
  if (\$masterHostname eq \$my_host){
    \$apm->sendParameters(\$clusterMaster, \$my_host, { "proofserv_count" => \$count, "xproofd_up" => \$xproofdup, "xrootd_up" => \$xrootdup, "cmsd_up" => \$olbdup, "aaf_xrootd_ver" => \$xrootd_ver, "aaf_xrootd_ver_latest" => \$xrootd_ver_latest,"aaf_root_ver" => \$root_ver,"aaf_proof_alias" => \$proof_alias,"aaf_proof_workers" => \$countWorkers,"aaf_status" => \$aaf_status});
  }

  sleep 120;
}

EOF


}
function RecreatingROOTLinks() {
  rm -f $AAF_DIR/root > /dev/null 2>&1
  rm -f $AAF_DIR/root_dbg > /dev/null 2>&1
  echo "ln -s $AAF_DIR/alien_packages/VO_ALICE/ROOT/$ROOT_VER/$ROOT_VER $AAF_DIR/root"
  ln -s $AAF_DIR/alien_packages/VO_ALICE/ROOT/$ROOT_VER/$ROOT_VER $AAF_DIR/root
#   echo "ln -s $AAF_DIR/alien_packages/VO_ALICE/ROOT/$ROOT_VER_DBG/$ROOT_VER_DBG $AAF_DIR/root_dbg"
#   ln -s $AAF_DIR/alien_packages/VO_ALICE/ROOT/$ROOT_VER_DBG/$ROOT_VER_DBG $AAF_DIR/root_dbg
}

function SyncGroupFile() {

  newname="groups.alice.cf"
  if [ "$ALICE_PROOF_AAF_PROOF_GROUP_UPDATE" = "1" ];then
    mv $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/$newname $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/${newname}.old
    wget -O $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/$newname http://xrootd-dm.googlecode.com/svn/trunk/etc/PROOF_AAF/macros/$newname > /dev/null 2>&1
  fi
  export ALICE_PROOF_AAF_PROOF_VARIABLES="ALICE_PROOF_AAF_DIR"
  ALICE_PROOF_AAF_PROOF_VARIABLES="ALICE_PROOF_AAF_PROOF_XPROOFD_DIR $ALICE_PROOF_AAF_PROOF_VARIABLES"

  # Substitute all the variables into the templates
  perl -pi -e "$ALICE_PROOF_AAF_PROOF_VARIABLES_PERL" $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/$newname;

}

function ModifyRootsysInProofconfig() {


  MY_PROOF_CF_FILE_TMP="$ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/prf-main.cf.new.rootsys"
  

  # remove all rootsys form prf-main.cf
  cat $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/prf-main.cf | grep -v 'xpd.rootsys' > $MY_PROOF_CF_FILE_TMP

  # add defaullt root sys
#   echo "" >> $MY_PROOF_CF_FILE_TMP
#   echo "# default root and root dbg" >> $MY_PROOF_CF_FILE_TMP

  echo "xpd.rootsys \$gRootsys VO_ALICE@ROOT::current" >> $MY_PROOF_CF_FILE_TMP
  # it will be removed soon
  echo "xpd.rootsys \$gRootsys current" >> $MY_PROOF_CF_FILE_TMP

#  echo "xpd.rootsys $ALIEN_PACKAGES_DIR/$MY_ALIEN_USER/ROOT/$ROOT_VER/$ROOT_VER current" >> $MY_PROOF_CF_FILE_TMP
#   echo "" >> $MY_PROOF_CF_FILE_TMP

  # add other available root versions
  if [ ! -z $1 ];then
    MY_ALIEN_USER=`echo $1 | awk -F '@' '{print $1}'`
    MY_ALIEN_PACKAGE=`echo $1 | awk -F '@' '{print $2}'`
    if [ -d $ALIEN_PACKAGES_DIR/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/ ]; then
#       echo "# additional root versions" >> $MY_PROOF_CF_FILE_TMP
      for MY_VER  in `ls $ALIEN_PACKAGES_DIR/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/`; do
	echo "xpd.rootsys $ALIEN_PACKAGES_DIR/$MY_ALIEN_USER/$MY_ALIEN_PACKAGE/$MY_VER/$MY_VER $MY_ALIEN_USER@$MY_ALIEN_PACKAGE::$MY_VER" >> $MY_PROOF_CF_FILE_TMP
      done
    fi
    cp -f $MY_PROOF_CF_FILE_TMP $ALICE_PROOF_AAF_PROOF_XPROOFD_DIR/prf-main.cf
  else
    echo "Empty package name !!!"
  fi  

}

function GenerateAAFEnv() {

rm -Rf $AAF_DIR/aaf_env.sh  > /dev/null 2>&1

echo "export ALICE_PROOF_AAF_DIR=$AAF_DIR" > $AAF_DIR/aaf_env.sh
# cat $AAF_DIR/proof/aaf-proof/scripts/aaf_env.sh >> $AAF_DIR/aaf_env.sh
echo "if [ -z \"\$ALICE_PROOF_AAF_DIR\" ]; then" >> $AAF_DIR/aaf_env.sh
echo "  echo \"Define \\\$ALICE_PROOF_AAF_DIR first !!!\" " >> $AAF_DIR/aaf_env.sh
echo "  exit 1" >> $AAF_DIR/aaf_env.sh
echo "fi" >> $AAF_DIR/aaf_env.sh
echo "export ALIEN_DIR=\"\$ALICE_PROOF_AAF_DIR/alien\"" >> $AAF_DIR/aaf_env.sh
echo "export ROOTSYS=\"\$ALICE_PROOF_AAF_DIR/root\" ">> $AAF_DIR/aaf_env.sh
echo "export LD_LIBRARY_PATH=\"\$ROOTSYS/lib:\$ALIEN_DIR/api/lib:\$ALIEN_DIR/lib:\$LD_LIBRARY_PATH\"" >> $AAF_DIR/aaf_env.sh
echo "export PATH=\"\$ROOTSYS/bin:\$ALIEN_DIR/api/bin:\$ALIEN_DIR/bin:\$PATH\" ">> $AAF_DIR/aaf_env.sh
echo "export X509_CERT_DIR=\"\$ALIEN_DIR/globus/share/certificates/\"" >> $AAF_DIR/aaf_env.sh
# ISHOST=`which host`
# if [ "$?" == "0" ];then
#   MYCLIENTS=`host alice-apiserv1.cern.ch | awk '{print $NF}' | awk '{ printf "%s:10000|",$0 }'`
#   echo "export GCLIENT_SERVER_LIST=\"$MYCLIENTS\"" >> $AAF_DIR/aaf_env.sh
# else 
  echo "export GCLIENT_SERVER_LIST=\"pcapiserv03.cern.ch:10000|\"" >> $AAF_DIR/aaf_env.sh
# fi


# echo "export GCLIENT_SERVER_LIST=\"pcapiserv08.cern.ch:10000|pcapiserv04.cern.ch:10000|pcapiserv07.cern.ch:10000|\"" >> $AAF_DIR/aaf_env.sh
echo "# generated `date`" > $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALIEN_PACKAGES_AFS_DIR=\"$AAF_DIR/alien_packages\"" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALIEN_PACKAGES_AFS_SCRIPTS_DIR=\"$AAF_DIR/scripts\"" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALIEN_DIR=\"$AAF_DIR/alien\"" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALICE_USERNAME=proof" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALICE_ROOT_VERSION_TYPE=\"AN\"" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALICE_CHECK_ALIEN_TOKEN=\"NO\"" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
echo "ALICE_CERTIFICATE_PATH=\"$AAF_DIR/.globus\"" >> $AAF_DIR/scripts/env_aliroot_aaf.bash

echo "source \$ALIEN_PACKAGES_AFS_SCRIPTS_DIR/env_aliroot.bash" >> $AAF_DIR/scripts/env_aliroot_aaf.bash
# 
# MY_ALIROOT=`find $ALIEN_PACKAGES_DIR/VO_ALICE/AliRoot/ -maxdepth 1 -mindepth 1 -type d | grep "AN" | awk -F/ '{print $NF}' | sort | tail -n1`
# MYVER=`ls -al $AAF_DIR/root | awk -F '/' '{ print $NF}'`
# 
# echo "source $AAF_DIR/scripts/env_aliroot_aaf.bash VO_ALICE@AliRoot::$MY_ALIROOT VO_ALICE@ROOT::$MYVER > /dev/null 2>&1" >  $AAF_DIR/aaf_env.sh
# # ln -s $AAF_DIR/scripts/env_aliroot_aaf.bash $AAF_DIR/aaf_env.sh

}


######### MAIN START #############
echo "Sync AliEn packages ..."
# create proof package dir
# if [ ! -d $PROOF_PACKAGES_DIR ]; then
#   mkdir -p $PROOF_PACKAGES_DIR
# fi

echo "\$ALICE_PROOF_AAF_PROOF_DIR is $ALICE_PROOF_AAF_PROOF_DIR ..."

rm -Rf $PROOF_PACKAGES_DIR
mkdir -p $PROOF_PACKAGES_DIR

rm -f $ALICE_PROOF_AAF_PROOF_DIR/aaf-aliroot
ln -s $THIS_DIR $ALICE_PROOF_AAF_PROOF_DIR/aaf-aliroot

if [ ! -d $ALICE_PROOF_AAF_PROOF_DIR/packages ]; then
  ln -s $THIS_DIR/packages $ALICE_PROOF_AAF_PROOF_DIR/
fi

SyncAAFMacrosAndScripts

for MY_PACKAGE in $PROOF_PACKAGES_LIST; do
  echo "  Sync $MY_PACKAGE ..."
  SyncOneAliEnPackage $MY_PACKAGE
done

SyncAFDSUtilsPar

echo "Sync AliEn packages done..."

# RecreatingROOTLinks

GenerateAAFmlclientPerlScript

GenerateAAFmlclientConfig

SyncGroupFile

ModifyRootsysInProofconfig VO_ALICE@ROOT

GenerateAAFEnv

echo " DONE installing $THIS_AAF_PACKAGE on `hostname -f` ..."
